# -*- coding: utf-8 -*-
# @Time    : 2024/04/30 10:02
# @Author  : Mr.su
# @FileName: bottegaveneta.py
# @FileDesc:
from CollectSpiders.settings import LOG_FILE_PATH
from CollectSpiders.toots.methods import make_md5
import scrapy, json, datetime, urllib.parse, logging
from CollectSpiders.toots.connects import RedisClient


# noinspection PyAbstractClass,PyMethodMayBeStatic
class CrawlSpider(scrapy.Spider):
    name, domain = 'bottegaveneta', 'www.bottegaveneta.cn'
    redisClient = RedisClient()
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
    }
    custom_settings = {
        'CONCURRENT_REQUESTS': 2,
        'LOG_FILE': LOG_FILE_PATH, 'LOG_LEVEL': 'WARNING'
    }

    def __init__(self, data=None, *args, **kwargs):
        """
        传入自定义参数
        :param data: 数据列表
        :param args:
        :param kwargs:
        """
        super(CrawlSpider, self).__init__(*args, **kwargs)
        self.data = json.loads(urllib.parse.unquote(data)) if data else {
            "pid": "1200", "status": 1, "wait_time": 3600, "brand": "bottegaveneta",
            "childs": {
                "1101": {
                    "sid": "1201", "label": "男", "upload": 1, "status": 1, "webtype": "taobao",
                    "url": "https://www.bottegaveneta.cn/categories/men.html?pageSize=12"
                },
                "1102": {
                    "sid": "1102", "label": "女", "upload": 1, "status": 1, "webtype": "taobao",
                    "url": "https://www.bottegaveneta.cn/categories/women.html?pageSize=12"
                }
            }
        }

    def start_requests(self):
        column = list(self.data['childs'].values())[0]
        if column['status'] == 1:
            _page = column['url'].split('?')[0].split('/')[-1]
            start_url = 'https://www.bottegaveneta.cn/rest/default/V2/catalog/productListByUrl?url={}&pageSize=24&page={}'
            yield scrapy.Request(
                start_url.format(_page, 1), headers=self.headers, callback=self.process_lis,
                meta={'column_url': start_url, '_page': _page, 'pg': 1, 'column': column}
            )

    def process_lis(self, response):
        column = response.meta['column']
        js = json.loads(response.text)
        has_more = True
        for item in js['data']['items']:
            result = self.redisClient.conn.sadd('products', make_md5(item['url']))
            if not result:
                has_more = False
                break
            img_lis = item['attributes'][0]['values'][0]['imageList']['desktopImageList']
            product = {
                '_id': make_md5(img_lis[0]),
                'pid': self.data['pid'],
                'sid': column['sid'],
                'status': '0',  # 0:未下载  1:已下载  6:下载失败
                'webtype': column['webtype'],
                'url': 'https://www.bottegaveneta.cn/products{}'.format(item['url']),
                'time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'brand': self.data['brand'],
                'image': img_lis,
                'domain': self.domain,
                'label': column['label'],
                'upload': column['upload'],
                'name': item['name']
            }
            logging.warning('<{}>: 数据id: {}'.format(self.domain, product['_id']))
            yield product
        if has_more:
            pg = response.meta['pg'] + 1
            if pg <= js['data']['totalPages']:
                _page = response.meta['_page']
                column_url = response.meta['column_url']
                yield scrapy.Request(
                    column_url.format(_page, pg), headers=self.headers, callback=self.process_lis,
                    meta={'column_url': column_url, '_page': _page, 'pg': pg, 'column': column}
                )
